package com.dynamic.datasource.transaction;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.util.StringUtils;

/**
 * @author www
 * @description: 本地事务拦截
 * @date 2022/4/5 21:04
 */
public class LocalTransactionInterceptor implements MethodInterceptor {

    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        if (!StringUtils.isEmpty(TransactionContext.get())) {
            return methodInvocation.proceed();
        }
        boolean state = true;
        Object o;
        TransactionUtil.start();
        try {
            o = methodInvocation.proceed();
        } catch (Exception e) {
            state = false;
            throw e;
        } finally {
            if (state) {
                TransactionUtil.commit();
            } else {
                TransactionUtil.rollback();
            }
        }
        return o;
    }
}
